package com.dianrui.fmi.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.R;
import com.dianrui.fmi.adapter.MessageAdapter;
import com.dianrui.fmi.bean.MessageModel;
import com.dianrui.fmi.event.RfreshUnread;
import com.dianrui.fmi.interfaces.MsgDeleteClick;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshListView;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Message
 */

public class MessageListActivity extends BaseActivity implements MsgDeleteClick{
    private ProgressDialog mProgressDialog;
    private MessageAdapter messageAdapter;
    private int mPageIndex = 1;
    private List<MessageModel> mMessageList = new ArrayList<>();

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.msg_listview)
    PullToRefreshListView msgListview;
    @BindView(R.id.msg_emptyView)
    LinearLayout msgEmptyView;

    @Override
    public int getContentViewId() {
        return R.layout.activity_msg_list;
    }

    @Override
    public void initView() {
        mProgressDialog = new ProgressDialog(MessageListActivity.this);
        title.setText(getString(R.string.main_msg_txt));
        rightImg.setVisibility(View.VISIBLE);
        rightImg.setImageResource(R.mipmap.msg_del);
        messageAdapter=new MessageAdapter(MessageListActivity.this,mMessageList,this);
        msgListview.setAdapter(messageAdapter);
        getMsgList(false);
        msgListview.setMode(PullToRefreshBase.Mode.BOTH);
        messageAdapter.setOnMessageClickListener(new MessageAdapter.MessageClickAdapter() {
            @Override
            public void onClick(String id, TextView title, TextView contents, TextView date) {
                startActivity(new Intent(MessageListActivity.this,MessageDeatilsActivity.class).putExtra("id",id));
                title.setTextColor(getResources().getColor(R.color.nav_color_txt));
                contents.setTextColor(getResources().getColor(R.color.nav_color_txt));
                date.setTextColor(getResources().getColor(R.color.nav_color_txt));
            }

        });
        msgListview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMsgList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mPageIndex++;
                getMsgList(false);

            }
        });
    }



    public void getMsgList(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("p", mPageIndex);
        OkHttpUtils.getInstance().postWithMemberToken(Url.MESSAGELIST, jsonObject.toString(),  new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (msgListview != null) {
                    msgListview.onRefreshComplete();
                }
                if (isRfresh) {
                    mMessageList.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        MessageModel messageModel = new MessageModel();
                                        messageModel.message_id = jsonArray.optJSONObject(i).optString("messages_id");
                                        messageModel.title = jsonArray.optJSONObject(i).optString("title");
                                        messageModel.content = jsonArray.optJSONObject(i).optString("contents");
                                        messageModel.create_time = jsonArray.optJSONObject(i).optString("create_time");
                                        messageModel.is_read = jsonArray.optJSONObject(i).optInt("is_read");
                                        mMessageList.add(messageModel);
                                    }
                                    if (messageAdapter != null) {
                                        messageAdapter.refresh(mMessageList);
                                    }
                                    rightImg.setEnabled(true);


                                }else {
                                    rightImg.setEnabled(false);
                                    msgEmptyView.setVisibility(View.VISIBLE);
                                    msgListview.setVisibility(View.GONE);
                                }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (mMessageList.size() <= 0) {
                        msgEmptyView.setVisibility(View.VISIBLE);
                        msgListview.setVisibility(View.GONE);
                    } else {
                        msgEmptyView.setVisibility(View.GONE);
                        msgListview.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (msgListview != null) {
                        msgListview.onRefreshComplete();
                    }
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    @OnClick({R.id.back, R.id.right_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_img://Msg all del
                AlertDialog.Builder builder = new AlertDialog.Builder(MessageListActivity.this, R.style.RcDialog);
                View view1 = LayoutInflater.from(MessageListActivity.this).inflate(R.layout.dialog_msgdel_ask, null);
                final AlertDialog dialog = builder.create();
                dialog.setView(view1);
                TextView cancel_dialog_ask = view1.findViewById(R.id.cancel_dialog_ask);
                final TextView yes_dialog_ask = view1.findViewById(R.id.yes_dialog_ask);
                cancel_dialog_ask.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                yes_dialog_ask.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        MsgAllDelete();
                    }
                });
                if (!MyUtil.getActivity(dialog.getContext()).isFinishing()) {
                    dialog.show();
                }

                break;

            default:
                break;
        }

    }

    @Override
    public void MessageDeleteClick(int pos,String msg_id) {
        MsgDelete(pos,msg_id);
    }

    //单个消息删除
    private void MsgDelete(final int position,String msgId) {
        JsonObject delmsgJsonobject = new JsonObject();
        delmsgJsonobject.addProperty("messages_id", msgId);
        OkHttpUtils.getInstance().postWithMemberToken(Url.DELMEESSAGE, delmsgJsonobject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (msgListview != null) {
                    msgListview.onRefreshComplete();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                mMessageList.remove(position);
                                EventBus.getDefault().post(new RfreshUnread());
                                messageAdapter.refresh(mMessageList);
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }



    private void MsgAllDelete() {
        JsonObject delAllmsgJsonobject = new JsonObject();
        delAllmsgJsonobject.addProperty("messages_id", "0");
        delAllmsgJsonobject.addProperty("del_all", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.DELMEESSAGE, delAllmsgJsonobject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (msgListview != null) {
                    msgListview.onRefreshComplete();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                EventBus.getDefault().post(new RfreshUnread());
                                getMsgList(true);
                                messageAdapter.refresh(mMessageList);
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        super.onDestroy();
    }
}
